package net.liteheaven.xblib.plugin;

import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;

/**
 * 插件管理类
 *
 * Created by LiangYu on 16/8/29
 */
public class XPluginManager {

    private HashMap<String, XPlugin> mPluginMap = new HashMap<>();

    XPluginManager(){
    }

    public XPlugin get(String pluginName) throws XPluginException {
        if (TextUtils.isEmpty(pluginName)){
            throw new XPluginException("插件名为空");
        }

        XPlugin plugin = mPluginMap.get(pluginName);
        if (plugin == null){
            XPlugin loaded = loadPlugin(pluginName);
            mPluginMap.put(pluginName, loaded);
            plugin = loaded;
        }

        if (plugin == null){
            throw new XPluginException("插件空，未知异常");
        }

        return plugin;
    }

    private XPlugin loadPlugin(String pluginName) throws XPluginException{
        if (TextUtils.isEmpty(pluginName)){
            throw new XPluginException("插件名不能为空");
        }

        String ext = PathUtil.getExternalApkPath(pluginName);
        log("ext = " + ext);
        String inn = PathUtil.getInnerApkPath(pluginName);
        log("inn = " + inn);

        // 1.检查外部包是否存在，如果存在则覆盖到内部包
        boolean isExtValid = fileExists(ext);
        log("ext valid = " + isExtValid);
        if (isExtValid){
            boolean copyResult = copyFile(ext, inn);
            log("copy file result = " + copyResult);
        }

        // 2.不管是否经过拷贝，内部包存在则插件创建成功
        if (!fileExists(inn)){
            throw new XPluginException("plugin package does not exist.");
        }

        XPlugin plugin = new XPlugin.Builder()
                .setApkPath(pluginName)
                .build();

        return plugin;
    }

    private static boolean copyFile(String oldPath, String newPath) {
        try {
            int byteSum = 0;
            int byteRead;
            File oldFile = new File(oldPath);
            if (oldFile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ( (byteRead = inStream.read(buffer)) != -1) {
                    byteSum += byteRead; //字节数 文件大小
                    System.out.println(byteSum);
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            XPluginLog.i(e);
            return false;
        }
        return true;
    }

    private static boolean fileExists(String path){
        boolean isPathValid = false;
        if (!TextUtils.isEmpty(path)){
            File f = new File(path);
            try{
                if (f.isFile()){
                    isPathValid = true;
                }
            }catch (Exception e){
                XPluginLog.i(e);
                isPathValid = false;
            }
        }
        return isPathValid;
    }

    private static void log(String content){
        System.out.println(content);
    }
}
